package com.scau.wrongtitle.service;

import com.scau.wrongtitle.bean.UserSubjectInfo;
import com.scau.wrongtitle.domin.TitleRecord;
import com.scau.wrongtitle.domin.UserInfo;
import com.scau.wrongtitle.repository.TitleRecordRepository;
import com.scau.wrongtitle.repository.UserInfoRepository;
import com.scau.wrongtitle.repository.WrongTitleRepository;
import com.scau.wrongtitle.util.Convert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class UserInfoService {
    private final UserInfoRepository userInfoRepository;
    private final WrongTitleRepository wrongTitleRepository;

    @Autowired
    public UserInfoService(UserInfoRepository userInfoRepository, WrongTitleRepository wrongTitleRepository) {
        this.userInfoRepository = userInfoRepository;
        this.wrongTitleRepository = wrongTitleRepository;
    }

    public List<String> getUserGrades(long id){
        List<String> list = userInfoRepository.getUserGrades(id);
        Collections.sort(list, (o1, o2) -> {
            if (o1.equals("知识竞赛"))
                return 1;
            if (o2.equals("知识竞赛"))
                return -1;
            if (o1.equals("六年级"))
                return 1;
            if (o2.equals("六年级"))
                return -1;
            if (o1.equals("五年级"))
                return 1;
            if (o2.equals("五年级"))
                return -1;
            if (o1.equals("四年级"))
                return 1;
            if (o2.equals("四年级"))
                return -1;
            if (o1.equals("三年级"))
                return 1;
            if (o2.equals("三年级"))
                return -1;
            if (o1.equals("二年级"))
                return 1;
            if (o2.equals("二年级"))
                return -1;
            if (o1.equals("一年级"))
                return 1;
            if (o2.equals("一年级"))
                return -1;
            return 0;
        });
        return list;
    }

    public List<UserSubjectInfo> getUserSubject(long id, String grade){
        List<UserSubjectInfo> list = new ArrayList<>();
        for (Map<String, Object> subject : wrongTitleRepository.getUserSubjects(id,grade))
            list.add(Convert.mapToUserSubjectInfo(subject));
        return list;
    }

    public UserInfo getUserInfoById(long id){
        return userInfoRepository.findById(id);
    }

    public void saveUserInfo(UserInfo info){
        userInfoRepository.save(info);
    }

    public void addUserWrongTitleCount(long id){
        UserInfo info = userInfoRepository.findById(id);
        info.setWrongTitleCount(info.getWrongTitleCount() + 1);
        userInfoRepository.save(info);
    }
}
